package com.aiyige.page.advertisement;

import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.VideoView;

import com.aiyige.R;
import com.aiyige.arouter.Router;
import com.aiyige.arouter.config.ARouterConfig;
import com.aiyige.base.db.table.AdFile;
import com.aiyige.base.db.table.AdModel;
import com.aiyige.page.advertisement.util.AdUtil;
import com.aiyige.page.player.PlayerInfo;
import com.aiyige.page.player.PlayerView;
import com.aiyige.utils.ListUtil;
import com.aiyige.utils.StringUtils;
import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions;
import com.bumptech.glide.request.RequestOptions;
import com.netease.nim.uikit.common.util.C;
import com.yqritc.scalablevideoview.ScalableVideoView;

import java.util.LinkedList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

@Route(path = ARouterConfig.AdPage)
public class AdPage extends AppCompatActivity {
    public static final long MAX_COUNT_DOWN_TIME_MS = 4000;
    public static final long COUNT_DOWN_INTERVAL_MS = 1000;
    public static final long WELCOME_VIDEO_LOCK_TIME_MS = 5000;
    @Autowired
    AdModel adModel = null;
    @BindView(R.id.adIv)
    ImageView adIv;
    @BindView(R.id.imageAdContainer)
    FrameLayout imageAdContainer;
    @BindView(R.id.videoAdContainer)
    FrameLayout videoAdContainer;
    @BindView(R.id.logoContainer)
    FrameLayout logoContainer;
    @BindView(R.id.skipAdBtn)
    TextView skipAdBtn;
    @BindView(R.id.videoPlayer)
    PlayerView videoPlayer;

    AdFile adFile;
    CountDownTimer countDownTimer;
    @BindView(R.id.welcomeVideoPlayer)
    ScalableVideoView welcomeVideoPlayer;
    @BindView(R.id.welcomeVideoPlayerContainer)
    View welcomeVideoPlayerContainer;
    @BindView(R.id.welcomeVideoClickLayout)
    View welcomeVideoClickLayout;
    CountDownTimer welcomeVideoCountTimer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.page_ad);
        ButterKnife.bind(this);
        ARouter.getInstance().inject(this);
        if (adModel == null || ListUtil.isEmpty(adModel.getAdFileList())) {
            finish();
            return;
        }
        videoPlayer.setPlayCallback(new PlayerView.PlayCallback() {
            @Override
            public void playChange(int position) {

            }

            @Override
            public void buy() {

            }

            @Override
            public void orientation(boolean landscape) {

            }

            @Override
            public void downloadVideos() {

            }

            @Override
            public void onPlaying() {

            }

            @Override
            public void onComplete() {
                finish();
            }

            @Override
            public void onError(int errorCode, String errorDetail) {
                finish();
            }
        });
        adFile = adModel.getAdFileList().get(0);
        countDownTimer = new CountDownTimer(MAX_COUNT_DOWN_TIME_MS, COUNT_DOWN_INTERVAL_MS) {
            @Override
            public void onTick(long millisUntilFinished) {
                if (isFinishing()) return;
                skipAdBtn.setText(millisUntilFinished / 1000 + " " + StringUtils.getString(R.string.skip_ad));
            }

            @Override
            public void onFinish() {
                if (isFinishing()) return;
                skipAdBtn.setText(R.string.skip_ad);
                finish();
            }
        };
        welcomeVideoCountTimer = new CountDownTimer(WELCOME_VIDEO_LOCK_TIME_MS, COUNT_DOWN_INTERVAL_MS) {
            @Override
            public void onTick(long millisUntilFinished) {
            }

            @Override
            public void onFinish() {
                if (isFinishing()) return;
                welcomeVideoClickLayout.setEnabled(true);
            }
        };
        switch (adFile.getFileType()) {
            case AdUtil.AD_FILE_TYPE_IMAGE:
                playImageAd();
                break;
            case AdUtil.AD_FILE_TYPE_VIDEO:
                playVideoAd();
                break;
            case AdUtil.AD_FILE_TYPE_WELCOME_VIDEO:
                playWelcomeVideo();
                break;
            default:
                finish();
                return;
        }
    }

    @Override
    protected void onDestroy() {
        countDownTimer.cancel();
        super.onDestroy();
    }

    public void playImageAd() {
        showImageAdContainer();
        Glide.with(this)
                .load(adFile.getFileLocalUrl())
                .apply(RequestOptions.placeholderOf(R.color.white))
                .transition(DrawableTransitionOptions.withCrossFade())
                .into(adIv);
        countDownTimer.start();
    }

    public void playVideoAd() {
        showVideoAdContainer();
        List<PlayerInfo> playerInfoList = new LinkedList<>();
        playerInfoList.add(new PlayerInfo(adFile.getFileLocalUrl(), "", "", true));
        videoPlayer.start(playerInfoList, 0);
    }

    public void playWelcomeVideo() {
        showWelcomeVideoContainer();
        welcomeVideoClickLayout.setEnabled(false);
        try {
            welcomeVideoPlayer.setRawData(adFile.getFileResId());
            welcomeVideoPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    welcomeVideoClickLayout.setEnabled(true);
                }
            });
            welcomeVideoPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                @Override
                public boolean onError(MediaPlayer mp, int what, int extra) {
                    finish();
                    return true;
                }
            });
            welcomeVideoPlayer.prepareAsync(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    if (isFinishing()) return;
                    welcomeVideoPlayer.start();
                    welcomeVideoCountTimer.start();
                }
            });
        } catch (Exception e) {
            System.out.println(e);
            finish();
        }
    }

    public void showWelcomeVideoContainer() {
        imageAdContainer.setVisibility(View.INVISIBLE);
        videoAdContainer.setVisibility(View.INVISIBLE);
        welcomeVideoPlayerContainer.setVisibility(View.VISIBLE);
    }

    public void showImageAdContainer() {
        imageAdContainer.setVisibility(View.VISIBLE);
        videoAdContainer.setVisibility(View.INVISIBLE);
        welcomeVideoPlayerContainer.setVisibility(View.INVISIBLE);
    }

    public void showVideoAdContainer() {
        imageAdContainer.setVisibility(View.INVISIBLE);
        videoAdContainer.setVisibility(View.VISIBLE);
        welcomeVideoPlayerContainer.setVisibility(View.INVISIBLE);
    }

    @OnClick({R.id.clickLayout, R.id.skipAdBtn, R.id.welcomeVideoClickLayout})
    public void onViewClicked(View view) {
        if (isFinishing()) return;
        switch (view.getId()) {
            case R.id.clickLayout:
                Router.start(adFile.getRouter(), adModel.getAdId());
                finish();
                break;
            case R.id.welcomeVideoClickLayout:
                finish();
                break;
            case R.id.skipAdBtn:
                finish();
                break;
        }
    }
}
